# -*- coding: utf-8 -*-

def index():
    search = FORM(TABLE(
        TR("宝贝名称:", INPUT(_type="text", _name="product_keys"),INPUT(_type="submit", _value="搜索", _style='padding: 0 5px;', requires=IS_NOT_EMPTY())),
        ))
    if search.accepts(request.vars, session):
        if request.vars.product_keys:
            redirect(URL(r=request, f='search', vars={'keys':request.vars.product_keys}))
        else:
            pass
    return dict(
        search = search,
        )
    
def search():
    size = 10
    now_page = 0
    if request.args:
        now_page = int(request.args[0])
    keys = request.vars['keys']
    # 取得商品信息
#    rsp = sip.taobao.products.search(
    rsp = sip.taobao.items.get(
        q=keys, 
        fields=['name', 'pic_path', 'product_id', 'cid', 'props', 'props_str', 'binds_str', 'desc', 'productImg'], 
        page_size=size, 
        page_no=now_page,
        )
    try:
        # 分离出商品列表和商品总数
        products = rsp['rsp']['products']
        totalResults = int(rsp['rsp']['totalResults'])
    except KeyError:
        session.flash = '没有符合的商品'
        redirect(URL(r=request, f='index'))
    
    search = FORM(TABLE(
        TR("重新搜索:", INPUT(_type="text", _name="product_keys"),INPUT(_type="submit", _value="搜索", _style='padding: 0 5px;', requires=IS_NOT_EMPTY())),
        ))
    if search.accepts(request.vars, session):
        if request.vars.product_keys:
            redirect(URL(r=request, f='search', vars={'keys':request.vars.product_keys}))
        else:
            session.flash = '没有符合的商品'
            redirect(URL(r=request))

    page = totalResults/size
    if now_page > 0 and now_page < page:
        page_up = A('上页', _href=URL(r=request, args=now_page-1, vars={'keys':keys}))
        page_down = A('下页', _href=URL(r=request, args=now_page+1, vars={'keys':keys}))
    elif now_page == 0:
        page_up = A('上页', _href=URL(r=request, args=page, vars={'keys':keys}))
        page_down = A('下页', _href=URL(r=request, args=now_page+1, vars={'keys':keys}))
    elif now_page == page:
        page_up = A('上页', _href=URL(r=request, args=now_page-1, vars={'keys':keys}))
        page_down = A('下页', _href=URL(r=request, args=0, vars={'keys':keys}))

    return dict(
        search = search,
        products = products,
        totalResults = totalResults,
        start = now_page*10,
        end = now_page*10+10 ,
        page_up = page_up,
        page_down = page_down,
        page = page,
        )
    
    